package com.common.base.utils

import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.os.LocaleList
import android.util.Log
import com.common.base.R
import java.util.*


/**
 * 作者：sosou
 *
 *
 * 版本：1.0
 *
 *
 * 创建日期：2022/5/29
 *
 *
 * 描述：多语言切换的帮助类
 *
 *
 * 修订历史：
 */
class MultiLanguageUtil private constructor() {
    /**
     * 如果不是英文、简体中文、繁体中文，默认返回简体中文
     *
     * @return
     */
    fun getLanguageLocale(context: Context?): Locale {
        val languageType: Int = SpUtilsManagement.getInt(SAVE_LANGUAGE, LanguageType.LANGUAGE_CHINESE_SIMPLIFIED)
        var locale = Locale.SIMPLIFIED_CHINESE
        if (languageType == LanguageType.LANGUAGE_FOLLOW_SYSTEM) {
            locale = mCurrentSystemLocal
        } else if (languageType == LanguageType.LANGUAGE_EN) {
            locale = Locale.ENGLISH
        } else if (languageType == LanguageType.LANGUAGE_CHINESE_SIMPLIFIED) {
            locale = Locale.SIMPLIFIED_CHINESE
        } else if (languageType == LanguageType.LANGUAGE_CHINESE_TRADITIONAL) {
            locale = Locale.TRADITIONAL_CHINESE
        }
        Log.e(TAG, "getLanguageLocale  " + getLanguage(locale))
        return locale
    }

    private fun getLanguage(locale: Locale): String {
        return locale.language + "_" + locale.country
    }

    /**
     * 不要获取系统的Locale直接来判断系统语言，不同的rom获取的Locale会有差别,可以通过Locale的language字段来判断语言
     * 比如华为手机的中文语言下Locale为zh_CN_#Hans
     * @return
     */
    fun getSysLocale(): Locale {
        return mCurrentSystemLocal
    }

    fun saveSystemCurrentLanguage(context: Context?) {
        val locale: Locale
        locale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LocaleList.getDefault()[0]
        } else {
            Locale.getDefault()
        }
        mCurrentSystemLocal = locale
    }

    /**
     * 更新语言
     * @param context
     * @param languageType
     */
    fun updateLanguage(context: Context?, languageType: Int) {
        SpUtilsManagement.putInt(SAVE_LANGUAGE, languageType)
        setConfiguration(context)
//        LiveEventBus.get(KeyEvents.KEY_CHANGE_LANGUAGE_RESULT).post(languageType)
    }

    fun getLanguageName(context: Context): String {
//        val languageType: Int = SpUtilsManagement.getInt(SAVE_LANGUAGE, LanguageType.LANGUAGE_FOLLOW_SYSTEM)
        val languageType: Int = SpUtilsManagement.getInt(SAVE_LANGUAGE, LanguageType.LANGUAGE_CHINESE_SIMPLIFIED)
        if (languageType == LanguageType.LANGUAGE_EN) {
            return context.getString(R.string.setting_language_english)
        } else if (languageType == LanguageType.LANGUAGE_CHINESE_SIMPLIFIED) {
            return context.getString(R.string.setting_simplified_chinese)
        } else if (languageType == LanguageType.LANGUAGE_CHINESE_TRADITIONAL) {
            return context.getString(R.string.setting_traditional_chinese)
        }
        return context.getString(R.string.setting_language_auto)
    }

    /**
     * 获取到用户保存的语言类型
     *
     * @return
     */
    fun getLanguageType(context: Context?): Int {
//        val languageType: Int = SpUtilsManagement.getInt(SAVE_LANGUAGE, LanguageType.LANGUAGE_FOLLOW_SYSTEM)
        val languageType: Int = SpUtilsManagement.getInt(SAVE_LANGUAGE, LanguageType.LANGUAGE_CHINESE_SIMPLIFIED)
        if (languageType == LanguageType.LANGUAGE_CHINESE_SIMPLIFIED) {
            return LanguageType.LANGUAGE_CHINESE_SIMPLIFIED
        } else if (languageType == LanguageType.LANGUAGE_CHINESE_TRADITIONAL) {
            return LanguageType.LANGUAGE_CHINESE_TRADITIONAL
        }
        else if (languageType == LanguageType.LANGUAGE_FOLLOW_SYSTEM) {
            return LanguageType.LANGUAGE_FOLLOW_SYSTEM
        }
        Log.e(TAG, "getLanguageType  $languageType")
        return languageType
    }

    /**
     * 设置语言
     */
    fun setConfiguration(context: Context?) {
        if (context == null) {
            Log.e(TAG, "No context, MultiLanguageUtil will not work!")
            return
        }
        val appContext = context.applicationContext
        Log.e(TAG, "setConfiguration $context")
        val targetLocale = getLanguageLocale(appContext)
        Locale.setDefault(targetLocale)
        val configuration = appContext.resources.configuration
        configuration.setLocale(targetLocale)
        context.createConfigurationContext(configuration)
        val resources = appContext.resources
        val dm = resources.displayMetrics
        resources.updateConfiguration(configuration, dm) //语言更换生效的代码!
    }

    /**
     * 设置语言类型
     */
    fun setApplicationLanguage(context: Context) {
        val resources = context.resources
        val dm = resources.displayMetrics
        val config = resources.configuration
        val locale = getLanguageLocale(context)
        config.locale = locale
        Log.e(TAG, "setApplicationLanguage  " + getLanguageName(context))
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val localeList = LocaleList(locale)
            LocaleList.setDefault(localeList)
            config.setLocales(localeList)
            context.createConfigurationContext(config)
            Locale.setDefault(locale)
        }
        resources.updateConfiguration(config, dm)
    }

    companion object {
        private const val TAG = "MultiLanguageUtil"
        var instance: MultiLanguageUtil? = null
            get() {
                if (field == null) {
                    synchronized(MultiLanguageUtil::class.java) {
                        if (field == null) {
                            field = MultiLanguageUtil()
                        }
                    }
                }
                return field
            }
            private set
        private const val SAVE_LANGUAGE = "save_language"
        private var mCurrentSystemLocal = Locale.CHINESE
        fun attachBaseContext(context: Context): Context {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                updateResources(context)
            } else {
                instance!!.setConfiguration(context)
                context
            }
        }

        @TargetApi(Build.VERSION_CODES.N)
        private fun updateResources(context: Context): Context {
            val resources = context.resources
            val configuration = resources.configuration
            val locale = instance!!.getLanguageLocale(context)
            Log.d(TAG, "getLanguage \${getLanguage(locale)}")
            val localeList = LocaleList(locale)
            LocaleList.setDefault(localeList)
            configuration.setLocales(localeList)
            configuration.setLocale(locale)
            return context.createConfigurationContext(configuration)
        }
    }
}